package com.zh.mp.demo.interceptor;

import com.zh.mp.demo.constants.Consts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class SessionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String token = (String) session.getAttribute(Consts.SESSION_KEY);
        if (token != null) {
            return true;
        }
        // 跳转到登录页
        String url = "/error";
        response.sendRedirect(request.getContextPath() + url);
        return false;
    }
}
